﻿/// <reference path="../jquery-1.6.2.min.js" />

var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {

    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string")
            obj = '"' + obj + '"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);

        for (n in obj) {
            v = obj[n]; t = typeof (v);

            if (t == "string") v = '"' + v + '"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);

            json.push((arr ? "" : '"' + n + '":') + String(v));
        }

        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
    if (str === "") str = '""';
    eval("var p=" + str + ";");
    return p;
};

(function ($) {
    $.fn.formSerialize = function () {
        var $form = $('<form id="x-virtual-form" />');
        $(this).wrap($form);
        var dataArr = $('form#x-virtual-form').serializeArray();
        $(this).unwrap();

        var obj = {};

        $.each(dataArr, function (i, o) {
            if (obj[o.name])
                obj[o.name] = $.makeArray(obj[o.name]).concat([o.value]);
            else
                obj[o.name] = o.value;
        });

        return obj;
    };
})(jQuery);


var Ecrms = {};

!(function (page) {

    $.ajaxSetup({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        global: false,
        type: "POST"
    });

    page.ajax = (function () {
        var url = '/Services/Service.svc/web/';
        var maskCss = {
            'color': '#FF0000',
            'font-size': '13px',
            'font-weight': 'bold',
            'height': '19px',
            'padding': '5px 10px',
            'position': 'absolute'
        };

        var $mask = null;

        return {
            mask: function (message) {
                if (!$mask) {
                    $mask = $('<div />').css(maskCss);
                    $(document.body).append($mask);
                }

                var frame = window.parent.mainFrame || window;
                var height = $(frame).height();
                var width = $(frame).width();

                $mask.css({
                    'color': '#FF0000',
                    'top': (height - 38) + 'px',
                    'width': (width - 25) + 'px'
                }).text(message || 'loading...').show();
            },

            unmask: function (message) {
                if (message) {
                    $mask.css({
                        'color': '#00EE33'
                    }).text(message);
                }

                $mask.hide('slow');
            },

            invoke: function (method, data, callback) {
                var me = this;

                var invokeUrl = url + method;
                var requestJson = JSON.stringify(data);

                $.ajax({
                    data: requestJson,
                    url: invokeUrl,
                    beforeSend: function () {
                        me.mask('数据加载中...');
                    },
                    complete: function () {
                        me.unmask('完成.');
                    },
                    success: function (response) {
                        if (!response) {
                            callback();
                            return;
                        }

                        var responseJson = (typeof response == 'string')
                                ? JSON.parse(response) : response;

                        var result = responseJson.Result;
                        if (result && callback) {
                            callback(result.status, result.message, result.data);
                        }
                    }
                });
            }
        }
    })();


    var resetPage = function () {
        var $hd = $('#header');
        var $wp = $('#wrapper');
        var $menu = $('#main-menu');
        var $frame = $('#mainFrame');

        var bodyHeight = $(window).height() - $hd.height();
        var frameWidth = $(window).width() - $menu.width();
        $wp.height(bodyHeight);
        $frame.height(bodyHeight - 2).width(frameWidth - 11);
    };

    page.init = function () {
        resetPage();

        $(window).resize(function () {
            resetPage();
        });
    };

    page.login = function (data) {

        var data = { username: 'abc', password: 'def' };
        page.ajax.invoke('Login', data,
            function (status, message) {
                if (status == 200) {
                    document.location = '/Default.aspx';
                }
                else {
                    alert('用户名或者密码错误！');
                }
            });
    }

    page.logout = function () {
        page.ajax.invoke('Logout', null, function () { document.location = document.location; });
    }

    page.changePwd = function (data) {
        page.ajax.invoke('ChangePassword', data,
            function (status, message) {
                if (status == 200) {
                    // alert('密码修改成功！');
                }
                else {
                    alert(message);
                }
            });
    }

})(Ecrms);